package com.education.service.impl;

import com.education.common.Const;
import com.education.common.RequestHolder;
import com.education.dao.*;
import com.education.pojo.Admin;
import com.education.pojo.Function;
import com.education.pojo.LoginConut;
import com.education.service.IManageUserService;
import com.education.utils.JsonMapper;
import com.education.utils.MD5Util;
import com.education.vo.FunctionAdminVo;
import com.education.vo.MonthWeekTodayYesterDayVo;
import com.education.vo.TotalVo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @author 林心晨
 * @Title:
 * @Package
 * @Description:    管理员逻辑层
 * @date create in 4.19  17:45
 */
@Service("iManageUserService")
@Transactional
public class ManageUserServiceImpl implements IManageUserService {

    private static Logger logger = LoggerFactory.getLogger(ManageUserServiceImpl.class);

    @Autowired
    private AdminMapper adminMapper ;

    @Autowired
    private RoleFunctionMapper roleFunctionMapper;

    @Autowired
    private FunctionMapper functionMapper ;

    @Autowired
    private LoginConutMapper loginConutMapper ;

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private QuestionMapper questionMapper ;

    @Autowired
    private SysCacheService sysCacheService ;

    /**
     * 对密码进行MD5+slat加密,查询出Admin用户信息
     * @param username  用户名
     * @param password  密码
     * @return  admin用户pojo对象
     */
    public Admin login(String username ,String password){
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        Admin admin = adminMapper.selectByUsernamePwd(username, md5Password);
        if (admin == null){
            return null;
        }
        /* 添加登录次数 */
        if (!accessedLogin(admin.getaId())){
            return null;
        }

        // TODO: 4.20 将密码置空 ，在返回给控制层
        admin.setaPassword(StringUtils.EMPTY);
        return admin;
    }

    /*public String storeAdminLoginSessionInRedis(){
        Admin currentAdmin = RequestHolder.getCurrentAdmin();


    }*/


    /**
     * 查询当前用户登录次数
     * @param adminId   管理员Id
     * @return
     */
    public LoginConut loginCount(Integer adminId){
        if (adminId == null){
            return null ;
        }
        LoginConut loginConut = loginConutMapper.selectByAdminId(adminId);
        if (loginConut == null){
            return null ;
        }
        return loginConut ;
    }

    /**
     * 计算管理员 用户 题库	图片库总数
     * @return
     */
    public TotalVo calculateTotal(){
        TotalVo totalVo = assembleTotal();
        if (totalVo != null){
            return totalVo ;
        }
        return null ;
    }

    // TODO: 4.26 创建时间不大于今天的总时间，就代表是今天的新增人数
    public MonthWeekTodayYesterDayVo categoryAddCount(){
        return this.assembleYearMonthDayToal();
    }

    /**
     *  验证用户名
     * @param username
     * @return
     */
    public boolean validUsername(String username){
        String rowCount = adminMapper.selectByUsernameValid(username);
        if (StringUtils.isBlank(rowCount)){
            return true ;
        }
        return false ;
    }

    public List getRootNodeAll(){
        Admin currentAdmin = RequestHolder.getCurrentAdmin();
        String md5str = MD5Util.MD5EncodeUtf8(currentAdmin.getaUsername());
        String cacheDba = sysCacheService.getFromCache(Const.CacheKeyConstants.SYSTEM_ACLS,md5str);
        if (StringUtils.isBlank(cacheDba)){
            List<Function> roleFunctionList = functionMapper.selectRootNode();
            List functionLists = Lists.newArrayList();
            for (Function item : roleFunctionList){
                /* 查询所有子节点 */
                
                FunctionAdminVo functionAdminVo = null ;
                if (item != null){
                    functionAdminVo = new FunctionAdminVo();
                    functionAdminVo.setfId(item.getfId());
                    functionAdminVo.setfName(item.getfName());
                    functionAdminVo.setParentId(item.getParentId());
                    functionAdminVo.setfUrl(item.getfUrl());
                    functionAdminVo.setfStatus(item.getfStatus());
                    List<Function> functionList = functionMapper.selectChildFunctionByParentId(item.getfId());
                    if (CollectionUtils.isNotEmpty(functionList)){
                        functionAdminVo.setFunctionList(functionList);
                    }
                }
                functionLists.add(functionAdminVo);
            }
            if (CollectionUtils.isNotEmpty(functionLists)){
                sysCacheService.saveCache(JsonMapper.obj2String(functionLists),
                        600 ,
                        Const.CacheKeyConstants.SYSTEM_ACLS,md5str);
            }
            return functionLists;
        }
        return JsonMapper.string2Obj(cacheDba, new TypeReference<List>() {});


    }


    /**
     * 返回今天，这周，这个月的数据记录
     * @return
     */
    private MonthWeekTodayYesterDayVo assembleYearMonthDayToal(){
        MonthWeekTodayYesterDayVo m = new MonthWeekTodayYesterDayVo();
        // TODO: 4.26 查询用户的创建时间 (where条件进行筛选)并对筛选的进行统计
        DateTime date = new DateTime();
        DateTime today = date.millisOfDay().withMaximumValue();
        DateTime yesterday = today.minusDays(1).millisOfDay().withMaximumValue();
        /* 管理员今日的注册总数 */
        Integer adminTotal = adminMapper.selectByToday(yesterday.toDate(),today.toDate());
        /* 用户今日的注册总数 */
        Integer userTotal = userMapper.selectByToday(yesterday.toDate(),today.toDate());
        /* 题库今日的注册总数 */
        Integer questionTotal = questionMapper.selectByToday(yesterday.toDate(),today.toDate());
        List<Integer> todayList = Lists.newArrayList();
        todayList.add(adminTotal);
        todayList.add(userTotal);
        todayList.add(questionTotal);
        m.setTodayDate(todayList);
        // TODO: 4.26 本周的增加数量 ,
        Integer adminWeek = adminMapper.selectByWeek(DateTime.now().dayOfWeek().withMinimumValue().toDate()
                , DateTime.now().dayOfWeek().withMaximumValue().toDate());
        Integer userWeek = userMapper.selectByWeek(DateTime.now().dayOfWeek().withMinimumValue().toDate()
                , DateTime.now().dayOfWeek().withMaximumValue().toDate());
        Integer questionWeek = questionMapper.selectByWeek(DateTime.now().dayOfWeek().withMinimumValue().toDate()
                , DateTime.now().dayOfWeek().withMaximumValue().toDate());
        List<Integer> weekList = Lists.newArrayList();
        weekList.add(adminWeek);
        weekList.add(userWeek);
        weekList.add(questionWeek);
        m.setWeekDate(weekList);
        // TODO: 4.26 本月的增加数量
        Integer adminMonth = adminMapper.selectByMonth(DateTime.now().dayOfMonth().withMinimumValue().toDate()
                , DateTime.now().dayOfMonth().withMaximumValue().toDate());
        Integer userMonth = userMapper.selectByMonth(DateTime.now().dayOfMonth().withMinimumValue().toDate()
                , DateTime.now().dayOfMonth().withMaximumValue().toDate());
        Integer questionMonth = questionMapper.selectByMonth(DateTime.now().dayOfMonth().withMinimumValue().toDate()
                , DateTime.now().dayOfMonth().withMaximumValue().toDate());
        List<Integer> monthList = Lists.newArrayList();
        monthList.add(adminMonth);
        monthList.add(userMonth);
        monthList.add(questionMonth);
        m.setMonthDate(monthList);
        return m ;
    }



    /**
     * 验证现在的时间是否包含在一天时间内
     * @param dateTime
     * @return
     */
    private boolean validDate(DateTime dateTime){
        if (dateTime == null){
            return false ;
        }
        DateTime date = new DateTime();
        /* 获取今天的最后的时分秒 */
        DateTime todayOverTime = date.millisOfDay()
                                .withMaximumValue();

        /* 获取昨天最后的时分秒 */
        DateTime yesterDay = todayOverTime
                            .minusDays(1)
                            .millisOfDay()
                            .withMaximumValue();

        Interval interval = new Interval(yesterDay,todayOverTime);
        return interval.contains(dateTime);
    }

    /**
     * 复用类，传入结果值进行判断
     * @param rowCount
     * @return  如果大于0，return true ；小于0 ，return false .
     */
    private boolean judgeRowCount(Integer rowCount){
        if (rowCount == null){
            return false ;
        }
        if (rowCount > 0){
            return true ;
        }
        return false ;
    }

    /**
     * 记录用户登录情况
     * @param adminId
     * @return
     */
    private boolean accessedLogin(Integer adminId){
        if (adminId == null){
            return false ;
        }
        LoginConut loginConut = loginConutMapper.selectByAdminId(adminId);
        if (loginConut == null){
            return false ;
        }
        if (loginConut.getAdminId() == adminId){
            loginConut.setCounts(loginConut.getCounts()+1);
            loginConut.setLastAccessedIp(getServerIp());/* 获取IP地址方法 */
            loginConutMapper.updateByPrimaryKeySelective(loginConut);   /* update */
            // TODO: 4.26 上次登录时间应该先于更新被读取
        }else {
            LoginConut lc = new LoginConut();
            lc.setAdminId(adminId);
            lc.setLastAccessedIp(getServerIp()); /* 获取IP地址方法 */
            loginConutMapper.insertByLoginCount(lc);
        }
        return true ;
    }

    /**
     * 后去当前服务器IP地址
     * @return
     */
    private static String getServerIp(){
        String SERVER_IP = null ;
        try {
            InetAddress address = InetAddress.getLocalHost();
            SERVER_IP = address.getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("获取当前服务器ip异常：",e);
        }
        return SERVER_IP ;
    }

    /**
     * 封装 管理员 用户 题库	图片库总数的vo对象
     * @return
     */
    private TotalVo assembleTotal(){
        TotalVo totalVo = new TotalVo();
        /* 查询所有管理员的总数 */
        Integer rowCountAdmin = adminMapper.selectByAdminTotal(Const.AdminProfileType.ADMIN.getCode());
        if (rowCountAdmin != null){
            totalVo.setAdminTotal(rowCountAdmin);
        }
        /* 查询所有用户的总数 */
        Integer rowCountUser = userMapper.selectByTotal();
        if (rowCountUser != null){
            totalVo.setUserTotal(rowCountUser);
        }

        /* 查询所有题库 */
        Integer rowCountQuestion = questionMapper.selectByTotal();
        if (rowCountQuestion != null){
            totalVo.setTotalTestLibrary(rowCountQuestion);
        }
        // TODO: 4.26  查询所有图片总数
        totalVo.setPhotoTotal(0);
        return totalVo ;
    }




}
